package cn.zniot.so.transport.server;

import cn.zniot.so.application.constant.Constants;
import cn.zniot.so.transport.exception.NetException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * Http服务器
 */
public class HttpServer extends ServerAdapter {
	private static final Log logger = LogFactory.getLog(HttpServer.class);

	private ThreadPoolExecutor threadPool = null;

	public NioSocketAcceptor acceptor = null;

	private  int port;
	private  int threadNum;
	
	public HttpServer(int serverPort,int threadNum) {
		this.port = serverPort;
		this.threadNum=threadNum;
	}
	
	@Override
	public void init(){
		this.acceptor = new NioSocketAcceptor();
		DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
		this.threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(this.threadNum);
		chain.addLast("threadPool", new ExecutorFilter(this.threadPool));
		// 绑定逻辑处理器 
		this.acceptor.setHandler(new HttpProtocolHandler());
	}
	
	@Override
	public void startup() throws NetException {
		try
		{
			this.acceptor.bind(new InetSocketAddress(this.port));
		} catch (IOException e)
		{
			throw new NetException("Http端口绑定异常",e);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("Http Server is listening on port " + this.port);
		}
	}

	@Override
	public void shutdown() throws NetException
	{
		super.shutdown();
	}
}
